package com.netty.service;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cxt
 * @date 2021/8/28
 * netty服务端请求处理类
 */
@Slf4j
public class NettyServerHandle extends SimpleChannelInboundHandler<FullHttpRequest> {

    // 存储已经连接的对象
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 存储用户id和用户的channelId绑定
    public static ConcurrentHashMap<Integer, ChannelId> userMap = new ConcurrentHashMap<>();

    // 用于存储群聊房间号和群聊成员的channel信息
    public static ConcurrentHashMap<Integer, ChannelGroup> groupMap = new ConcurrentHashMap<>();

    /**
     * 新建连接
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("新建连接{}", ctx.toString());
        // 添加到通道组中
        channelGroup.add(ctx.channel());
        ChannelId id = ctx.channel().id(); // 获取通道id
        super.channelActive(ctx);
    }

    /**
     * 通道读取
     *
     * @param ctx 上下文对象，含有通道channel
     * @param msg 客户端发送的数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("通道读取{}", ctx.toString());
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            Integer userId = getUrlParams(uri);
            // 用户id和用户的channelId绑定
            userMap.put(Objects.requireNonNull(Objects.requireNonNull(getUrlParams(uri))), ctx.channel().id());
            log.info("登录的用户id是：{}", userId);
        }
        super.channelRead(ctx, msg);
    }

    /**
     * 接收到消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        log.info("接受到消息:{}", channelHandlerContext);
        log.info(String.valueOf(fullHttpRequest));
    }

    /**
     * 接收到消息
     */
//    @Override
//    protected void messageReceived(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
//        log.info("接受到消息:{}", channelHandlerContext);
//        log.info(String.valueOf(fullHttpRequest));
//    }

    /**
     * 关闭连接
     *
     * @param ctx 上下文对象，含有通道channel
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端断开连接，通道关闭！");
        // 通道组移除
        channelGroup.remove(ctx.channel());
    }

    private static Integer getUrlParams(String url) {
        if (!url.contains("=")) {
            return null;
        }
        String userId = url.substring(url.indexOf("=") + 1);
        return Integer.parseInt(userId);
    }

}
